import { useEffect, useRef, DependencyList } from "react";
import _ from 'lodash';

type TOptions = {
    onScrollEnd?: Function;
    onScroll?: Function;
}

const useScroll = (options?: TOptions, deps?: DependencyList) => {
    const ref = useRef();

    const _onScroll = _.debounce((e) => {
        let scrollTop = e.target.scrollTop;
        let clientHeight = e.target.clientHeight;
        let scrollHeight = e.target.scrollHeight;

        if (scrollTop + clientHeight === scrollHeight) {
            options.onScrollEnd && options.onScrollEnd();
        }
        options.onScroll && options.onScroll({
            scrollTop,
            clientHeight,
            scrollHeight
        })
    }, 500);

    const getToTop = () => {
        if (ref.current) {
            (ref.current as HTMLElement).scrollTop = 0;
        }
    }

    useEffect(() => {
        if (ref.current) {
            (ref.current as HTMLElement).addEventListener('scroll', _onScroll)
        }
        () => {
            if (ref.current) {
                (ref.current as HTMLElement).removeEventListener('scroll', _onScroll)
            }
        }
    }, deps)

    return {
        ref,
        onScroll: _onScroll,
        getToTop
    }

}

export default useScroll